package smashedapples.google.language
{
	import com.adobe.serialization.json.JSON;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import smashedapples.google.GoogleLanguageApi;
	import smashedapples.core.Command;
	import smashedapples.core.Request;
	
	public class GoogleLanguageRequest extends Request
	{
		/**
		 * Constructor 
		 * @param command
		 * @param text
		 * @param langpair
		 * @param result
		 * @param fault
		 * 
		 */		
		public function GoogleLanguageRequest(command:Command,text:String,langpair:LangPairVO,result:Function,fault:Function=null):void
		{	
			super(command);
			
			this.text = text;
			this.langpair=langpair;
			this.result = result;
			this.fault = fault;
		
		}
		
		public var text : String;
		public var langpair : LangPairVO;
		public var result : Function;
		public var fault : Function;
		
		/**
		 * sends your request to the google api
		 * @param showBusyCursor
		 * @return AsyncToken
		 * 
		 */		
		public function send(showBusyCursor:Boolean=false):AsyncToken
		{

			var service : HTTPService = new HTTPService(null,"DefaultHTTP");
				service.url = GoogleLanguageApi.Static.URL;
				service.method = "GET";
				service.resultFormat = "text";
				service.useProxy = false;
				service.showBusyCursor = showBusyCursor;
		
				service.addEventListener(ResultEvent.RESULT, resultHandler );
				
				if(fault != null)
					service.addEventListener(FaultEvent.FAULT, this.fault );
			
			var params : Object = {};
				params["context"] = "22";
				params["langpair"] = langpair.value; 
				params["format"] = "text";
				params["q"] = this.text;
				params["v"] = "1.0";
				
			
			return service.send(params);
		}
		
		
		/**
		 *  handles the result, parses the JSON and dispatches the Response to your handler;
		 * @param event ResultEvent
		 * 
		 */		
		private function resultHandler(event:ResultEvent):void
		{
			var rawData:String = String(event.result);
			var obj:Object = (JSON.decode(rawData) as Object);
			
			
			var response : GoogleLanguageResponse = new GoogleLanguageResponse(this.command);
				
				response.originalText = this.text;
		
				response.responseStatus = Number( obj["responseStatus"] );
				response.responseDetails = Object( obj["responseDetails"] );
				if(response.responseStatus == 200)
				{
					response.translatedText = String(obj["responseData"]["translatedText"]);
				}
				
				
			this.result(response );
		}
		
		

	}
}